<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\admin;

use app\manage\model\admin\CodeGenerateColumn;
use app\manage\model\admin\CodeGenerateTable;
use buwang\base\AdminBaseController;
use buwang\traits\CrudControllerTrait;
use think\facade\Db;

class CodeGeneratorController extends AdminBaseController
{
    use CrudControllerTrait;

    protected $model = null;//模型实例

    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 获取数据库表信息
     */
    public function getDataTable()
    {
        $page = request()->get('page/d', 1);
        $limit = request()->get('limit/d', 10);
        $name = request()->get('name');
        $comment = request()->get('comment');
        $data = [
            'lists' => $this->lists($page, $limit, $name, $comment),
            'count' => $this->count($name, $comment),
        ];
        return $this->success('successful', $data);
    }

    /**
     * 选择数据表
     */
    public function selectDataTable()
    {
        //验证
        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }
        $params = request()->post();

        $result = $this->validate($params, 'CodeGeneratorValidate.select');
        if (true === $result) {
            Db::startTrans();
            try {
                foreach ($params['table'] as $item) {
                    // 添加主表基础信息
                    $generateTable = CodeGenerateTable::initTable($item, $this->uid);
                    // 获取数据表字段信息
                    $column = CodeGenerateColumn::getTableColumn($item['name']);
                    // 添加表字段信息
                    CodeGenerateColumn::initTableColumn($column, $generateTable['id']);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error('出错了：' . $e->getMessage() . $e->getFile() . $e->getLine());
            }
            return $this->success('successful');
        }
    }

    /**
     * 获取已选择的数据表
     */
    public function getCodeGenerateTable()
    {
        $page = request()->get('page/d', 1);
        $limit = request()->get('limit/d', 10);
        $name = request()->get('name');
        $comment = request()->get('comment');

        $where = [];
        if (!empty($name)) {
            $where['table_name'] = $name;
        }
        if (!empty($comment)) {
            $where['table_comment'] = $comment;
        }

        $data = [
            'lists' => CodeGenerateTable::where($where)
                ->order(['id' => 'desc'])
                ->append(['template_type_desc'])
                ->page($page, $limit)
                ->select()
                ->toArray(),
            'count' => CodeGenerateTable::where($where)->count(),
        ];
        return $this->success('successful', $data);
    }

    /**
     * 获取已选择的数据表详情
     */
    public function getCodeGenerateTableDetail()
    {
        $id = request()->get('id/d', 0);
        if (!$id) {
            return $this->error('id不能为空');
        }
        $detail = CodeGenerateTable::with('table_column')
            ->findOrEmpty($id)
            ->toArray();
        if (!$detail) {
            return $this->error('数据不存在');
        }

        $options = CodeGenerateTable::formatTableData($detail);
        $detail['menu'] = $options['menu'];
        $detail['delete'] = $options['delete'];
        $detail['tree'] = $options['tree'];
        $detail['relations'] = $options['relations'];
        return $this->success('successful', $detail);
    }

    /**
     * 编辑已选择的数据表信息
     */
    public function editCodeGenerateTable()
    {
        $params = request()->post();
        $rule = [
            'id' => 'require',
            'table_name' => 'require',
            'table_comment' => 'require',
            'template_type' => 'require',
            'generate_type' => 'require',
            'module_name' => 'require',
            'table_column' => 'require',
        ];
        $this->validate($params, $rule);

        $detail = CodeGenerateTable::findOrEmpty($params['id'])->toArray();
        if (!$detail) {
            return $this->error('数据不存在');
        }
        $result = CodeGenerateTable::editCodeGenerateTable($params);
        return $this->success('successful');
    }

    /**
     * 同步字段-已选择的数据表信息
     */
    public function syncColumnCodeGenerateTable()
    {
        $params = request()->post();
        if (!isset($params['id']) || !$params['id']) {
            return $this->error('id不能为空');
        }
        $detail = CodeGenerateTable::findOrEmpty($params['id'])->toArray();
        if (!$detail) {
            return $this->error('数据不存在');
        }

        $result = CodeGenerateTable::syncColumnCodeGenerateTable($params);
        return $this->success('successful');

    }

    /**
     * 预览-已选择的数据表信息
     */
    public function previewCodeGenerateTable()
    {

    }

    /**
     * 生成代码-已选择的数据表信息
     */
    public function generateCodeGenerateTable()
    {

    }

    /**
     * 删除已选择的数据表信息
     */
    public function deleteCodeGenerateTable()
    {
        $ids = request()->post('id', []);
        if (!$ids) {
            return $this->error('id不能为空');
        }
        CodeGenerateTable::whereIn('id', $ids)->delete();
        CodeGenerateColumn::whereIn('table_id', $ids)->delete();
        return $this->success('successful');
    }


    /**
     * 处理列表
     * @param $page
     * @param $limit
     * @param $name
     * @param $comment
     * @return array
     */
    public function lists($page, $limit, $name, $comment): array
    {
        $lists = array_map("array_change_key_case", $this->queryResult($name, $comment));
        $offset = max(0, ($page - 1) * $limit);
        $lists = array_slice($lists, $offset, $limit, true);
        return array_values($lists);
    }

    /**
     * 获取数量
     * @param $name
     * @param $comment
     * @return int
     */
    public function count($name, $comment): int
    {
        return count($this->queryResult($name, $comment));
    }

    /**
     * 查询结果
     * @param $name
     * @param $comment
     * @return mixed
     */
    public function queryResult($name, $comment)
    {
        $sql = 'SHOW TABLE STATUS WHERE 1=1 ';
        if (!empty($name)) {
            $sql .= "AND name LIKE '%" . $name . "%'";
        }
        if (!empty($comment)) {
            $sql .= "AND comment LIKE '%" . $comment . "%'";
        }
        return Db::query($sql);
    }

}
